package com.techchat.backend.service.impl;

import com.techchat.backend.mapper.MessageMapper;
import com.techchat.backend.mapper.UserMapper;
import com.techchat.backend.model.Message;
import com.techchat.backend.model.User;
import com.techchat.backend.service.MessageService;
import com.techchat.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset; // Import ZoneOffset
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserMapper userMapper;
    private final MessageMapper messageMapper;
    private final MessageService messageService;
    private final SimpMessagingTemplate messagingTemplate;

    public UserServiceImpl(UserMapper userMapper, MessageMapper messageMapper, MessageService messageService, SimpMessagingTemplate messagingTemplate) {
        this.userMapper = userMapper;
        this.messageMapper = messageMapper;
        this.messageService = messageService;
        this.messagingTemplate = messagingTemplate;
    }

    @Override
    public void register(User user) {
        try {
            // For user registration, server's local time might be fine or also use UTC
            user.setCreatedAt(LocalDateTime.now()); // Or LocalDateTime.now(ZoneOffset.UTC)
            user.setAvatar(null);
            logger.info("注册用户: {}", user.getUsername());
            userMapper.insert(user);
            logger.info("用户注册成功: {}", user.getUsername());
        } catch (Exception e) {
            logger.error("注册失败: {}", user.getUsername(), e);
            throw new RuntimeException("注册失败", e);
        }
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    @Override
    public List<String> getAllNicknames() {
        return userMapper.findAllNicknames();
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.findAllUsers();
    }

    @Override
    public void updateNickname(String username, String newNickname) {
        try {
            User existing = userMapper.findByUsername(username);
            if (existing == null) {
                throw new RuntimeException("用户不存在: " + username);
            }
            String oldNickname = existing.getNickname();

            if (oldNickname.equals(newNickname)) {
                logger.info("用户 [{}] 尝试将昵称更新为相同值，操作跳过。", username);
                return;
            }

            logger.info("更新用户 [{}] 的昵称: {} -> {}", username, oldNickname, newNickname);

            userMapper.updateNickname(username, newNickname);
            messageMapper.updateSender(oldNickname, newNickname);

            logger.info("用户 [{}] 昵称更新成功，并同步了历史消息中的 sender", username);

            Message systemMessage = Message.builder()
                    .content(String.format("“%s” 已将昵称修改为 “%s”", oldNickname, newNickname))
                    .sender("系统提示")
                    .timestamp(LocalDateTime.now(ZoneOffset.UTC)) // MODIFIED: Use UTC for system message timestamp
                    .messageType(Message.MessageType.SYSTEM_NICKNAME_CHANGE)
                    .build();
            messageService.saveMessage(systemMessage);
            messagingTemplate.convertAndSend("/topic/public", systemMessage);

            logger.info("已发送昵称更改系统消息: {}", systemMessage.getContent());

        } catch (Exception e) {
            logger.error("更新昵称失败: 用户 [{}]", username, e);
            throw new RuntimeException("更新昵称失败", e);
        }
    }

    @Override
    public void updateAvatar(String username, String avatarUrl) {
        try {
            logger.info("更新用户 [{}] 的头像为 [{}]", username, avatarUrl);
            userMapper.updateAvatar(username, avatarUrl);
            logger.info("用户 [{}] 头像更新成功", username);
        } catch (Exception e) {
            logger.error("更新头像失败: 用户 [{}]", username, e);
            throw new RuntimeException("更新头像失败", e);
        }
    }
}
